package com.gzx.plugin.tjzy.modular.allocate.mapper;

import com.gzx.plugin.tjzy.modular.allocate.entity.GzxAllocateRecord;
import com.gzx.plugin.tjzy.modular.allocate.entity.vo.GzxAllocateRecordVo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import vip.xiaonuo.common.mapper.BaseMapperPlus;

import java.util.List;

/**
 * @author zjt
 * @description
 * @since 2024/9/20 上午9:39
 */
public interface GzxAllocateRecordMapper extends BaseMapperPlus<GzxAllocateRecord, GzxAllocateRecordVo> {

    @Insert("<script>" +
            "INSERT INTO gzx_allocate_record ( " +
            "batch_number, debtor_card_id, mediator_id,tenant_id,create_user, create_time) VALUES" +
            "<foreach collection='allocateCaseLogList' item='item' index='index' separator=','>" +
            "(#{item.batchNumber},#{item.debtorCardId},#{item.mediatorId}," +
            "#{item.tenantId},#{item.createUser},#{item.createTime})" +
            "</foreach>" +
            "</script>")
    void insertBatch(List<GzxAllocateRecord> allocateCaseLogList);

    /**
     * 批量保存分案记录
     *
     * @param valueSql
     */
    @Insert("<script>" +
            "INSERT INTO gzx_allocate_record (type, batch_number, debtor_card_id, mediator_id,tenant_id,create_user, create_time) " +
            "VALUES ${valueSql}" +
            "</script>")
    void insertBatchByValSql(String valueSql);

    /**
     * 根据批次号和债务人卡ID列表查询每组最新记录（按ID降序）
     *
     * @param batchNumber      批次号（精确匹配）
     * @param debtorCardIdList 债务人卡ID列表（IN查询）
     * @return 每个(batch_number, debtor_card_id)组合中ID最大的记录列表
     */
    @Select("<script>" +
            "SELECT id, `type`, batch_number, debtor_card_id " +
            "FROM ( " +
            "    SELECT id, type, batch_number, debtor_card_id, " +
            "    ROW_NUMBER() OVER (PARTITION BY batch_number, debtor_card_id ORDER BY id DESC) AS rn " +
            "    FROM gzx_allocate_record " +
            "    WHERE batch_number = #{batchNumber} " +
            "    <if test='debtorCardIdList != null and debtorCardIdList.size() > 0'> " +
            "        AND debtor_card_id IN " +
            "        <foreach collection='debtorCardIdList' item='cardId' open='(' separator=',' close=')'> " +
            "            #{cardId} " +
            "        </foreach> " +
            "    </if> " +
            ") t " +
            "WHERE rn = 1 " +
            "</script>")
    List<GzxAllocateRecord> selectLatestRecordsByBatchAndDebtorCards(
            @Param("batchNumber") String batchNumber,
            @Param("debtorCardIdList") List<String> debtorCardIdList);
}
